package org.apache.roller.weblogger.business.sitemap;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by satish on 2/15/15.
 */
public class SitemapBuilder {
    List<String> urls = new ArrayList<String>();

    public void addUrl(String url) {
        urls.add(url);
    }

    public void write(File file) throws IOException {
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
            writer.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
            writer.write("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
            for(String url : urls) {
                writer.write("\t<url>\n");
                writer.write("\t\t<loc>" + url + "</loc>\n");
                writer.write("\t</url>\n");
            }
            writer.write("</urlset>");
        } finally {
            if(writer != null) {
                writer.close();
            }
        }
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        builder.append("<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">\n");
        for(String url : urls) {
            builder.append("\t").append("<url>\n");
            builder.append("\t\t").append("<loc>").append(url).append("</loc>\n");
            builder.append("\t").append("</url>\n");
        }
        builder.append("</urlset>");
        return builder.toString();
    }
}
